package com.example.everying.service.appeal.impl;/*
 * 项目名称: everything
 * 文件名: AppealEvidenceServiceImpl
 * 作者: 张泽阳
 * 日期: 2025/6/20
 * 描述:
 */

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.constant.OrderConstants;
import com.example.everying.context.UserContext;
import com.example.everying.mapper.appeal.AppealEvidenceMapper;
import com.example.everying.model.dto.appeal.*;
import com.example.everying.model.dto.content.ArtInfoDto;
import com.example.everying.model.entity.appeal.AppealEvidence;
import com.example.everying.model.entity.content.ActivityApply;
import com.example.everying.model.entity.user.UserBalanceEntity;
import com.example.everying.model.entity.user.UserBalanceTransactionEntity;
import com.example.everying.model.vo.appeal.AppealEvidenceListVo;
import com.example.everying.model.entity.appeal.AppealRecord;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.service.appeal.AppealEvidenceService;
import com.example.everying.service.appeal.AppealRecordService;
import com.example.everying.service.content.ActivityApplyService;
import com.example.everying.service.content.ActivityArticleService;
import com.example.everying.service.user.UserBalanceService;
import com.example.everying.service.user.UserBalanceTransactionService;
import com.example.everying.utils.CampusException;
import com.example.everying.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class AppealEvidenceServiceImpl extends ServiceImpl<AppealEvidenceMapper, AppealEvidence> implements AppealEvidenceService {
    private static final String PLATFORM_USER_ID = "1"; // 平台用户ID

    @Autowired
    private AppealRecordService appealRecordService;

    @Autowired
    private ActivityArticleService activityArticleService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private UserBalanceTransactionService userBalanceTransactionService;

    @Autowired
    private ActivityApplyService activityApplyService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addAppeal(AddAppealDto addAppealDto) {
//        ActivityArticle articleById = activityArticleService.getArticleById(addAppealDto.getArticleId());
//        LambdaQueryWrapper<ActivityApply> applyQueryWrapper = new LambdaQueryWrapper<>();
//        applyQueryWrapper.eq(ActivityApply::getArtId, addAppealDto.getArticleId());
//        applyQueryWrapper.orderByDesc(ActivityApply::getAcceptedAt);
//        List<ActivityApply> applyList = activityApplyService.list(applyQueryWrapper);
//        ActivityApply apply = applyList.get(0);
//        String status = "未知";
//        if (articleById.getStatus().equals("1")) {
//            status = "1";
//        }
////        if (!(articleById.getStatus().equals("3") || apply.getOrdersStatus().equals("3"))) {
////            status = "5";
////
////        }
//        if ((articleById.getStatus().equals("3") && apply.getOrdersStatus().equals("1")) ||
//                (apply.getOrdersStatus().equals("3") && articleById.getStatus().equals("3"))) {
//            status = "5";
//        }
//
//        // 判断订单状态 1进行中5待确认
////        if (!(addAppealDto.getStatus().equals("1")) && !(addAppealDto.getStatus().equals("5"))){
////            return Result.fail("订单状态错误");
////        }
//        if (!(status.equals("1")) && !(status.equals("5"))) {
//            return Result.fail("订单状态错误");
//        }
        if (!checkActivityStatus(addAppealDto.getArticleId())){
            return Result.fail("订单状态错误");
        }
        ActivityArticle articleById = activityArticleService.getArticleById(addAppealDto.getArticleId());

        // 查询申诉记录表中是否存在申诉记录
        AppealRecord appealRecord = appealRecordService.getAppealByArticleIdAndUserId(addAppealDto);

        if (appealRecord == null) {


            articleById.setAppealStatus("0");
            articleById.setUpdateTime(LocalDateTime.now());
            boolean b = activityArticleService.updateById(articleById);
            log.info("{}", b);

            // todo 只有发布人和接单人才能申诉
            if (articleById.getApplyId() == null) {
                return Result.fail("任务还没有被申请");
            }
            if ((!articleById.getUserId().equals(UserContext.getUser().getId())) && (!articleById.getApplyId().equals(UserContext.getUser().getId()))) {
                return Result.fail("您不能申诉");
            }


            String apperlUserId = UserContext.getUser().getId();
            // 添加申诉记录
            AppealRecord saveAppealRecord = new AppealRecord();
            saveAppealRecord.setArticleId(addAppealDto.getArticleId());
            saveAppealRecord.setAppealUserId(apperlUserId);
            String beAppealUserId = articleById.getUserId().equals(apperlUserId) ? articleById.getApplyId() : articleById.getUserId();
            saveAppealRecord.setBeAppealUserId(beAppealUserId);
            saveAppealRecord.setMoney(articleById.getMoney());
            saveAppealRecord.setArticleType(articleById.getType());
            saveAppealRecord.setAppealStatus("0");
            saveAppealRecord.setAppealCount(1);
            saveAppealRecord.setCheckStatus("1");
            saveAppealRecord.setAppealTime(LocalDateTime.now());
            saveAppealRecord.setUpdateTime(LocalDateTime.now());

            appealRecordService.save(saveAppealRecord);

            // 添加申诉凭证
            AppealEvidence appealEvidence = new AppealEvidence();
            appealEvidence.setAppealId(saveAppealRecord.getId());
            appealEvidence.setContent(addAppealDto.getContent());
            appealEvidence.setPictureUrl(addAppealDto.getPictureUrl());
            appealEvidence.setUserId(UserContext.getUser().getId());
            appealEvidence.setEvidenceStatus("0");
            appealEvidence.setCreateTime(LocalDateTime.now());
            appealEvidence.setUpdateTime(LocalDateTime.now());
            appealEvidence.setEvidenceType("0");
            appealEvidence.setUserType(userTypeHandel(addAppealDto.getArticleUserId(), apperlUserId));
            save(appealEvidence);
            // 发送申诉通知
            sendAppealNotification(addAppealDto.getArticleId(), saveAppealRecord, "0", apperlUserId);
            // 发送被申诉通知
            sendBeAppealNotification(addAppealDto.getArticleId(), beAppealUserId);
            return Result.ok(saveAppealRecord);
        }
        if(appealRecord.getAppealStatus().equals("2") ){
            return Result.fail("你的申诉已经撤销，请勿重复申诉");
        }
        if(appealRecord.getAppealStatus().equals("3")){
            return Result.fail("你的申诉已经失败，请勿重复申诉");
        }
        return Result.fail("您已经申诉过了，请到申诉记录中发送补充凭证");
    }

    @Override
    public Result<?> addEvidence(AddEvidenceDto addEvidenceDto) {
//        if (!(addEvidenceDto.getStatus().equals("1")) && !(addEvidenceDto.getStatus().equals("2"))) {
//            return Result.fail("订单状态错误");
//        }

/*        ActivityArticle articleById = activityArticleService.getArticleById(addEvidenceDto.getArticleId());
        LambdaQueryWrapper<ActivityApply> applyQueryWrapper = new LambdaQueryWrapper<>();
        applyQueryWrapper.eq(ActivityApply::getArtId, addEvidenceDto.getArticleId());
        applyQueryWrapper.orderByDesc(ActivityApply::getAcceptedAt);
        List<ActivityApply> applyList = activityApplyService.list(applyQueryWrapper);
        ActivityApply apply = applyList.get(0);
        String status = "未知";
        if (articleById.getStatus().equals("1")) {
            status = "1";
        }
//        if (!(articleById.getStatus().equals("3") || apply.getOrdersStatus().equals("3"))) {
//            status = "5";
//
//        }
        if ((articleById.getStatus().equals("3") && apply.getOrdersStatus().equals("1")) ||
                (apply.getOrdersStatus().equals("3") && articleById.getStatus().equals("3"))) {
            status = "5";
        }

        // 判断订单状态 1进行中5待确认
//        if (!(addAppealDto.getStatus().equals("1")) && !(addAppealDto.getStatus().equals("5"))){
//            return Result.fail("订单状态错误");
//        }
        if (!(status.equals("1")) && !(status.equals("5"))) {
            return Result.fail("订单状态错误");
        }*/
        if (!checkActivityStatus(addEvidenceDto.getArticleId())){
            return Result.fail("订单状态错误");
        }

        // 获取申诉记录
        AppealRecord appealRecord = appealRecordService.getById(addEvidenceDto.getAppealId());
        if (appealRecord == null || !appealRecord.getArticleId().equals(addEvidenceDto.getArticleId())) {
            return Result.fail("申诉记录不存在");
        }
        if (!(appealRecord.getAppealStatus().equals("0"))) {
            return Result.fail("请勿重复申诉");
        }
        // 判断是申诉人还是被申诉人
        if (appealRecord.getAppealUserId().equals(UserContext.getUser().getId())) {
            if (appealRecord.getAppealCount() >= 3) {
                return Result.fail("您已经投诉了3次，请勿重复投诉");
            }
            appealRecord.setAppealCount(appealRecord.getAppealCount() + 1);
            appealRecord.setCheckStatus("1");
            appealRecord.setUpdateTime(LocalDateTime.now());
            boolean flag = appealRecordService.updateById(appealRecord);
            AppealEvidence appealEvidence = new AppealEvidence();
            BeanUtil.copyProperties(addEvidenceDto, appealEvidence);
            appealEvidence.setEvidenceStatus("0");
            appealEvidence.setEvidenceType("0");
            appealEvidence.setUserId(UserContext.getUser().getId());
            appealEvidence.setCreateTime(LocalDateTime.now());
            appealEvidence.setUpdateTime(LocalDateTime.now());
            appealEvidence.setUserType(userTypeHandel(addEvidenceDto.getArticleUserId(), UserContext.getUser().getId()));
            int evidenceFlag = baseMapper.insert(appealEvidence);
            if (flag && evidenceFlag > 0) {
                return Result.success("申诉人凭证上传成功");
            }
        } else if (appealRecord.getBeAppealUserId().equals(UserContext.getUser().getId()) || appealRecord.getBeAppealUserId() == null) {
            if (appealRecord.getBeAppealCount() >= 3) {
                return Result.fail("您已经投诉了3次，请勿重复投诉");
            }
            appealRecord.setBeAppealCount(appealRecord.getBeAppealCount() + 1);
            appealRecord.setCheckStatus("1");
            appealRecord.setUpdateTime(LocalDateTime.now());
            boolean flag = appealRecordService.updateById(appealRecord);
            AppealEvidence appealEvidence = new AppealEvidence();
            BeanUtil.copyProperties(addEvidenceDto, appealEvidence);
            appealEvidence.setEvidenceStatus("0");
            appealEvidence.setEvidenceType("1");
            appealEvidence.setUserId(UserContext.getUser().getId());
            appealEvidence.setCreateTime(LocalDateTime.now());
            appealEvidence.setUpdateTime(LocalDateTime.now());
            appealEvidence.setUserType(userTypeHandel(addEvidenceDto.getArticleUserId(), addEvidenceDto.getUserId()));
            int evidenceFlag = baseMapper.insert(appealEvidence);
            if (flag && evidenceFlag > 0) {
                return Result.success(appealEvidence);
            }

        }
        return Result.fail("上传失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> getAppealEvidenceList(GetAppealEvidenceDto getAppealEvidenceDto) {

        LambdaQueryWrapper<AppealRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
        recordQueryWrapper.eq(getAppealEvidenceDto.getArticleId() != null ,AppealRecord::getArticleId, getAppealEvidenceDto.getArticleId());
//        recordQueryWrapper.eq(AppealRecord::getAppealStatus, "0");
        recordQueryWrapper.orderByDesc(AppealRecord::getAppealTime);
        List<AppealRecord> recodes = appealRecordService.list(recordQueryWrapper);
        if (recodes == null || recodes.size() == 0) {
            return Result.fail("未查询到申诉记录");
        }
        Long appealId = recodes.get(0).getId();


        LambdaQueryWrapper<AppealEvidence> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppealEvidence::getAppealId, appealId);
        queryWrapper.orderByDesc(AppealEvidence::getCreateTime);
        List<AppealEvidence> list = list(queryWrapper);

        if (list != null && list.size() > 0) {
            AppealRecord appealRecord = appealRecordService.getById(appealId);
            if(UserContext.getUser().getIsAdministrator() == 1){
                appealRecord.setCheckStatus("0");
            }

//            appealRecord.setUpdateTime(LocalDateTime.now());
            boolean flag = appealRecordService.updateById(appealRecord);
            AppealEvidenceListVo appealEvidenceListVo = new AppealEvidenceListVo();
            appealEvidenceListVo.setMoney(appealRecord.getMoney());
            appealEvidenceListVo.setEvidenceList(list);
            appealEvidenceListVo.setStatus(appealRecord.getAppealUserId().equals(UserContext.getUser().getId()) ? "1" : "0");
            return Result.success(appealEvidenceListVo);
        }


        return Result.fail("未查询到凭证记录");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> checkAppealEvidence(CheckAppealEvidenceDto checkAppealEvidenceDto) {
        LambdaQueryWrapper<AppealEvidence> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(checkAppealEvidenceDto.getId() != null, AppealEvidence::getId, checkAppealEvidenceDto.getId());
        AppealEvidence appealEvidence = baseMapper.selectOne(queryWrapper);
        if (appealEvidence == null) {
            return Result.fail("未找到凭证记录");
        }
        if (!appealEvidence.getEvidenceStatus().equals("0")) {
            return Result.fail("凭证审核状态错误");
        }
        AppealEvidence checkEvidence = new AppealEvidence();
        checkEvidence.setAppealId(appealEvidence.getAppealId());
//        checkEvidence.setContent(checkAppealEvidenceDto.getReason());
        checkEvidence.setUserId(UserContext.getUser().getId());
        checkEvidence.setUserType("2");
        checkEvidence.setEvidenceStatus(checkAppealEvidenceDto.getEvidenceStatus());
        checkEvidence.setEvidenceType("3");
        checkEvidence.setCreateTime(LocalDateTime.now());
        checkEvidence.setUpdateTime(LocalDateTime.now());
//        int checkFlag = baseMapper.insert(checkEvidence);
        LambdaQueryWrapper<AppealEvidence> countQueryWrapper = new LambdaQueryWrapper<>();
        countQueryWrapper.eq(AppealEvidence::getAppealId, checkAppealEvidenceDto.getAppealId());
        countQueryWrapper.eq(AppealEvidence::getUserId, checkAppealEvidenceDto.getUserId());
        Long count = baseMapper.selectCount(countQueryWrapper);
        if (checkAppealEvidenceDto.getEvidenceStatus().equals("1")) {
            AppealRecord appealRecord = appealRecordService.getById(appealEvidence.getAppealId());
            if (appealRecord == null) {
                return Result.fail("未找到申诉记录");
            }
            if (appealRecord.getAppealStatus().equals("1") || appealRecord.getAppealStatus().equals("3")) {
                return Result.fail("申诉已处理");
            }

            checkEvidence.setContent("凭证内容为【" + appealEvidence.getContent() + "】的凭证审核通过" );

            appealEvidence.setEvidenceStatus(checkAppealEvidenceDto.getEvidenceStatus());
            appealEvidence.setUpdateTime(LocalDateTime.now());
            appealEvidence.setUpdateUser(UserContext.getUser().getId());
            int i = baseMapper.updateById(appealEvidence);
            // 更新申诉记录
            appealRecord.setAppealStatus(checkAppealEvidenceDto.getEvidenceStatus());
            appealRecord.setUpdateTime(LocalDateTime.now());
            boolean appealUpdateFlag = appealRecordService.updateById(appealRecord);
            if (i > 0 && appealUpdateFlag) {
                // todo 执行申诉成功之后的逻辑
                // 修改文章状态
                ActivityArticle activityArticle = activityArticleService.getById(appealRecord.getArticleId());
                activityArticle.setAppealStatus("3");
                activityArticle.setUpdateTime(LocalDateTime.now());
                boolean updateFlag = activityArticleService.updateById(activityArticle);
                // 开始扣费
                boolean refundFlag = handlerRefund(appealRecord);
                if (refundFlag) {
                    // 发送通知
                    sendAppealNotification(appealRecord.getArticleId(), appealRecord, "1", appealRecord.getAppealUserId());
                    sendAppealNotification(appealRecord.getArticleId(), appealRecord, "3", appealRecord.getBeAppealUserId());
                }
                int checkFlag = baseMapper.insert(checkEvidence);
                return refundFlag ? Result.ok("凭证审核成功") : Result.fail("退款失败，请稍后重试");
            }
        } else if (checkAppealEvidenceDto.getEvidenceStatus().equals("4") && count >=3) {
            AppealRecord appealRecord = appealRecordService.getById(appealEvidence.getAppealId());
            if (appealRecord == null) {
                return Result.fail("未找到申诉记录");
            }
            // 更新申诉记录
            appealRecord.setAppealStatus("3");
            appealRecord.setUpdateTime(LocalDateTime.now());
            boolean appealUpdateFlag = appealRecordService.updateById(appealRecord);

            checkEvidence.setContent("凭证内容为【" + appealEvidence.getContent() + "】的凭证审核失败\n 失败原因：" + checkAppealEvidenceDto.getReason());
            checkEvidence.setEvidenceStatus("3");
            int checkFlag = baseMapper.insert(checkEvidence);

            appealEvidence.setEvidenceStatus("3");
            appealEvidence.setUpdateTime(LocalDateTime.now());
            int updateEvidenceFlag = baseMapper.updateById(appealEvidence);
            if (appealUpdateFlag) {
                // 申述失败
                // 发送通知
                sendAppealNotification(appealRecord.getArticleId(), appealRecord, "3", appealRecord.getAppealUserId());
                sendAppealNotification(appealRecord.getArticleId(), appealRecord, "1", appealRecord.getBeAppealUserId());
            }
            ActivityArticle activityArticle = activityArticleService.getById(appealRecord.getArticleId());
            activityArticle.setAppealStatus("3");
            activityArticle.setUpdateTime(LocalDateTime.now());
            boolean updateFlag = activityArticleService.updateById(activityArticle);
            return Result.ok("凭证审核失败");

        } else if (checkAppealEvidenceDto.getEvidenceStatus().equals("4") && count < 3) {
            AppealRecord appealRecord = appealRecordService.getById(appealEvidence.getAppealId());
            checkEvidence.setContent("凭证内容为【" + appealEvidence.getContent() + "】的凭证审核失败\n 失败原因：" + checkAppealEvidenceDto.getReason());

            appealEvidence.setEvidenceStatus(checkAppealEvidenceDto.getEvidenceStatus());
            appealEvidence.setUpdateTime(LocalDateTime.now());
            int i = baseMapper.updateById(appealEvidence);
            int checkFlag = baseMapper.insert(checkEvidence);
            if (checkFlag > 0){
                // 发送通知
                sendAppealNotification(appealRecord.getArticleId(), appealRecord, "4", checkAppealEvidenceDto.getUserId());

            }
            return Result.ok("凭证不足");
        }

        return Result.fail("凭证审核失败");
    }


    private boolean handlerRefund(AppealRecord appealRecord) {
        ActivityArticle activityArticle = activityArticleService.getById(appealRecord.getArticleId());
        if (activityArticle == null) {
            log.error("文章不存在，ID: " + appealRecord.getArticleId());
            throw new CampusException("文章不存在", 201);
        }
        // 判断谁是付款人
        String payerId = activityArticleService.getRefundUserId(activityArticle);

        // 是不是付款人赢了
        if (payerId.equals(appealRecord.getAppealUserId())) {
            // 开始退款
            handleOrderCancelled(activityArticle, activityArticle.getMoney());
        }
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> cancelAppeal(CancelAppealDto cancelAppealDto) {

        LambdaQueryWrapper<AppealRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
        recordQueryWrapper.eq(cancelAppealDto.getArticleId() != null, AppealRecord::getArticleId, cancelAppealDto.getArticleId());
        recordQueryWrapper.eq(AppealRecord::getAppealUserId, UserContext.getUser().getId());
        recordQueryWrapper.eq(AppealRecord::getAppealStatus, "0");
        AppealRecord appealRecord = appealRecordService.getOne(recordQueryWrapper);
        if (appealRecord == null) {
            return Result.fail("未找到申诉记录");
        }
        appealRecord.setAppealStatus("2");
        appealRecord.setUpdateTime(LocalDateTime.now());
        boolean flag = appealRecordService.updateById(appealRecord);
        if (flag) {

            baseMapper.updateEvidenceCancelStatus(appealRecord.getId());

            ActivityArticle article = activityArticleService.getById(appealRecord.getArticleId());
            article.setAppealStatus("3");
            article.setUpdateTime(LocalDateTime.now());
            boolean articleFlag = activityArticleService.updateById(article);
            sendAppealNotification(appealRecord.getArticleId(), appealRecord, "2", appealRecord.getBeAppealUserId());

        }


/*        LambdaQueryWrapper<AppealRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(cancelAppealDto.getAppealId() != null,AppealRecord::getId,cancelAppealDto.getAppealId());
        AppealRecord appealRecord = appealRecordService.getOne(queryWrapper);
        if (!(appealRecord.getAppealUserId().equals(UserContext.getUser().getId()))){
            return Result.fail("被申诉人不能撤销申诉");
        }
        if (appealRecord == null){
            return Result.fail("未找到申诉记录");
        }
        if (appealRecord.getAppealStatus().equals("1")){
            return Result.fail("申诉通过后不能撤销");
        }
        if (appealRecord.getAppealStatus().equals("2")){
            return Result.fail("申诉已撤销");
        }
        appealRecord.setAppealStatus("2");
        appealRecord.setUpdateTime(LocalDateTime.now());
        boolean flag = appealRecordService.updateById(appealRecord);*/

        return Result.ok(appealRecord);
    }


    public String userTypeHandel(String articleUserId, String userId) {
        return articleUserId.equals(userId) ? "0" : "1";
    }

    /**
     * 处理已取消状态的订单
     * 向相应用户退款
     *
     * @param activityArticle 活动文章对象，包含退款金额和用户信息
     */
    protected void handleOrderCancelled(ActivityArticle activityArticle, BigDecimal amount) {
        String userId = activityArticleService.getRefundUserId(activityArticle);

        log.info("开始退钱，给{}退钱", userId);

        boolean isAdded = userBalanceService.addBalance(userId, amount);
        if (isAdded) {
            UserBalanceEntity userBalance = userBalanceService.getBalanceByUserId(userId);
            createAndSaveTransaction(
                    userId, activityArticle.getId(), amount,
                    userBalance.getAvailableAmount().add(amount),
                    OrderConstants.TYPE_USER_INCOME, "用户退款",
                    OrderConstants.USER_TYPE_USER, OrderConstants.ORDER_TYPE_REFUND
            );
        }

        // 系统用户扣款
        log.info("开始扣款，给系统扣款");
        boolean isDeducted = userBalanceService.deductBalance(PLATFORM_USER_ID, amount);
        if (isDeducted) {
            UserBalanceEntity platformBalance = userBalanceService.getBalanceByUserId(PLATFORM_USER_ID);
            boolean isSave = createAndSaveTransaction(
                    PLATFORM_USER_ID, activityArticle.getId(), amount,
                    platformBalance.getAvailableAmount().subtract(amount), OrderConstants.TYPE_PLATFORM_EXPENSE,
                    "用户退款", OrderConstants.USER_TYPE_PLATFORM, OrderConstants.ORDER_TYPE_REFUND
            );
            if (!isSave) {
                throw new CampusException("保存交易记录失败", 201);
            }
        }
    }

    // 公共方法：创建并保存交易记录
    private boolean createAndSaveTransaction(String userId, String txId, BigDecimal changeAmount, BigDecimal balanceAfterChange,
                                             String txType, String remark, String userType, String type) {
        log.info("开始保存交易记录，用户id{},业务id{},交易类型{}，用户类型{}", userId, txId, txType, userType);
        UserBalanceTransactionEntity transaction = new UserBalanceTransactionEntity();
        transaction.setUserId(userId);
        transaction.setTxId(userType.equals(OrderConstants.USER_TYPE_PLATFORM) ? "PL" + txId : txId);
        transaction.setChangeAmount(changeAmount);  // 微信单位为分
        transaction.setBalanceSnapshot(balanceAfterChange);
        transaction.setTxStatus(OrderConstants.TX_STATUS_SUCCESS);
        transaction.setTxType(txType);
        transaction.setRemark(remark);
        transaction.setUserType(userType);
        transaction.setType(type);
        boolean result = userBalanceTransactionService.save(transaction);
        log.info("保存交易结果：{}", result ? "成功" : "失败");
        return result;
    }

    /**
     * 发送申诉通知（根据角色+状态生成通知）
     *
     * @param artId        文章ID
     * @param appealRecord 申诉记录对象
     * @param appealStatus 申诉状态：0-申诉中, 1-审核通过, 2-撤销, 3-审核失败, 4-凭证不足
     * @param userId       接收通知的用户ID
     */
    public void sendAppealNotification(String artId, AppealRecord appealRecord, String appealStatus, String userId) {
        // 获取文章信息
        ActivityArticle article = activityArticleService.getById(artId);
        if (article == null) throw new CampusException("关联活动不存在", 201);
        String articleTitle = article.getTitle();

//        // 判断角色
//        boolean isAppealUserPublisher = appealRecord.getAppealUserId().equals(article.getUserId());
//        boolean isBeAppealUserPublisher = appealRecord.getBeAppealUserId().equals(article.getUserId());

        boolean isCurrentUserAppealer = appealRecord.getAppealUserId().equals(userId);
        boolean isCurrentUserBeAppealer = appealRecord.getBeAppealUserId().equals(userId);

        String role;
        String relation;

        if (isCurrentUserAppealer) {
//            role = isAppealUserPublisher ? "发布的" : "参与的";
            relation = "提交";
        } else if (isCurrentUserBeAppealer) {
//            role = isBeAppealUserPublisher ? "发布的" : "参与的";
            relation = "参与";
        } else {
            role = "平台管理员";
            relation = "";
        }

        // 构建通知内容
        String title, content;

        content = switch (appealStatus) {
            case "0" -> {
                title = "申诉处理中";
                yield String.format("您%s的申诉正在处理中，请耐心等待审核。", relation);
            }
            case "1" -> {
                title = "申诉审核通过";
                yield String.format("您%s的申诉已审核通过，相关权益将尽快恢复。", relation);
            }
            case "2" -> {
                title = "申诉已撤销";
                yield String.format("您%s的申诉已被撤销。", relation);
            }
            case "3" -> {
                title = "申诉审核失败";
                yield String.format("遗憾通知您，您%s的申诉未通过审核。", relation);
            }
            case "4" -> {
                title = "申诉凭证不充分";
                yield "您提交的申诉凭证不足，请补充后重新提交。";
            }
            default -> throw new IllegalArgumentException("未知的申诉状态: " + appealStatus);
        };
        ArtInfoDto artInfoDto = new ArtInfoDto();
        artInfoDto.setTitle(articleTitle);
        artInfoDto.setArticleId(article.getId());
        artInfoDto.setType(article.getType());
        artInfoDto.setArticleUserName(activityApplyService.getUserNickname(article.getUserId()));
        artInfoDto.setArticleUserAvatar(activityApplyService.getUserAvatar(article.getUserId()));
        activityApplyService.sendSystemNotification(userId, title, content, "6", JSON.toJSONString(artInfoDto));
    }

    // 发送被申诉通知 
    public void sendBeAppealNotification(String artId, String userId) {
        // 获取文章信息
        ActivityArticle article = activityArticleService.getById(artId);
        if (article == null) throw new CampusException("关联活动不存在", 201);
        String articleTitle = article.getTitle();
        String role = article.getUserId().equals(userId) ? "发布的" : "参与的";
        String content = String.format("你%s帖子被申诉，请尽快提交凭证以完成申诉处理。", role);
        ArtInfoDto artInfoDto = new ArtInfoDto();
        artInfoDto.setTitle(articleTitle);
        artInfoDto.setArticleId(article.getId());
        artInfoDto.setType(article.getType());
        artInfoDto.setArticleUserName(activityApplyService.getUserNickname(article.getUserId()));
        artInfoDto.setArticleUserAvatar(activityApplyService.getUserAvatar(article.getUserId()));
        activityApplyService.sendSystemNotification(userId, "申诉处理中", content, "6",  JSON.toJSONString(artInfoDto));
    }

    // 判断文章状态
    public boolean checkActivityStatus(String artId){
        ActivityArticle articleById = activityArticleService.getArticleById(artId);
        LambdaQueryWrapper<ActivityApply> applyQueryWrapper = new LambdaQueryWrapper<>();
        applyQueryWrapper.eq(ActivityApply::getArtId, artId);
        applyQueryWrapper.orderByDesc(ActivityApply::getAcceptedAt);
        List<ActivityApply> applyList = activityApplyService.list(applyQueryWrapper);
        ActivityApply apply = applyList.get(0);
        String status = "未知";
        if (articleById.getStatus().equals("1")) {
            status = "1";
        }
//        if (!(articleById.getStatus().equals("3") || apply.getOrdersStatus().equals("3"))) {
//            status = "5";
//
//        }
        if ((articleById.getStatus().equals("3") && apply.getOrdersStatus().equals("1")) ||
                (apply.getOrdersStatus().equals("3") && articleById.getStatus().equals("3"))) {
            status = "5";
        }

        // 判断订单状态 1进行中5待确认
//        if (!(addAppealDto.getStatus().equals("1")) && !(addAppealDto.getStatus().equals("5"))){
//            return Result.fail("订单状态错误");
//        }
        // status不等于1或5则返回false

        return status.equals("1") || status.equals("5");
    }


}
